package com.mengyu.moeisland.net

import android.content.Intent
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.mengyu.moeisland.bean.BaseBean
import com.mengyu.moeisland.net.ApiException.Companion.ERRORDATA
import com.mengyu.moeisland.net.ApiException.Companion.ERRORNET
import com.mengyu.moeisland.net.ApiException.Companion.ERRORNULL
import com.mengyu.moeisland.net.ApiException.Companion.ERRORPASER
import com.mengyu.moeisland.utils.LGG
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch


fun <T> FragmentActivity.requestNet( block: suspend () -> T? ,success: ((T) -> Unit)? = null , error: (ApiException) -> Unit = {}){
    lifecycleScope.requestNet(block,success,error)
}

fun <T> Fragment.requestNet( block: suspend () -> T? ,success: ((T) -> Unit)? = null , error: (ApiException) -> Unit = {}){
    lifecycleScope.requestNet(block,success,error)
}

fun <T> ViewModel.requestNet( block: suspend () -> T? ,success: ((T) -> Unit)? = null , error: (ApiException) -> Unit = {}){
    viewModelScope.requestNet(block,success,error)
}

fun <T> CoroutineScope.requestNet( block: suspend () -> T? ,success: ((T) -> Unit)? = null , error: (ApiException) -> Unit = {}){
    launch{
        runCatching {
            block()
        }.onSuccess{
            runCatching{
                LGG.e("e", "Result data:${it}")
                executeResponse(it, { t -> success?.let { it.invoke(t) } }, error)
            }.onFailure {
                error(ApiException("${it.message}",ERRORPASER))
                LGG.e("e", "Result message:${it.message}")
            }
        }.onFailure{
            error(ApiException("${it.message}",ERRORNET))
            LGG.e("e", "Result message:${it.message}")
        }
    }
}

suspend fun <T> executeResponse(response: T?,
                                success: suspend CoroutineScope.(T) -> Unit,
                                error: (ApiException) -> Unit){
    coroutineScope{
        if(response!=null){
            if(response is BaseBean<*>){ // 当前App的网络框架做特殊解析哦
                if(response.success){
                    success(response)
                }else{
                    if(response.code=="666666"){

                    }else  if(response.code=="302"){

                    } else{
                        error(ApiException(response.msg,ERRORDATA,response.code))
                    }
                }
            }else{
                success(response)
            }
        }else{
            error(ApiException("数据是null,---",ERRORNULL))
        }

    }
}
